package com.uziot.bucket.poi.office.excel;

import com.aspose.cells.*;

import java.io.*;
import java.util.UUID;

public class Excel2Img {

    public static void main(String[] args) {
        //new com.aspose.cells.License().setLicense();
        excelToPic("C:\\Users\\detao\\Desktop\\cc.xls", "C:\\Users\\detao\\Desktop\\");
    }

    /**
     * excel文件转换为PDF文件
     *
     * @param address    需要转化的Excel文件地址，
     * @param outputPath 转换后的文件地址
     */
    public static String excelToPic(String address, String outputPath) {
        String fileName = UUID.randomUUID() + ".png";
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return null;
        }
        try {
            Workbook wb = new Workbook(address);
            Worksheet sheet = wb.getWorksheets().get(0);
            sheet.getPageSetup().setLeftMargin(-20);
            sheet.getPageSetup().setRightMargin(0);
            sheet.getPageSetup().setBottomMargin(0);
            sheet.getPageSetup().setTopMargin(0);

            ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
            imgOptions.setImageType(ImageType.PNG);
            imgOptions.setCellAutoFit(true);
            imgOptions.setOnePagePerSheet(true);
            imgOptions.setDesiredSize(1600,900);
            SheetRender render = new SheetRender(sheet, imgOptions);
            render.toImage(0, outputPath + fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 获取认证，去除水印
     *
     * @return 是否成功
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            //这个文件应该是类似于密码验证(证书？)，用于获得去除水印的权限
            InputStream is = Excel2PdfUtil.class.getClassLoader().getResourceAsStream("/static/license.xml");
            License license = new License();
            license.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
